//
//  WordAIViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/9.
//

#import "WordAIViewController.h"
#import "WordListModel.h"
#import "AiChatManager.h"

@interface WordAIViewController ()<JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UIButton *translateBtn;
@property(nonatomic,strong)UILabel *contentLabel;
@property(nonatomic,strong)UILabel *translateLabel;
@property(nonatomic,strong)AiChatManager *aiChatManager;
@property(nonatomic,copy)NSString *contentStr;
@property(nonatomic,copy)NSString *translateStr;
@property(nonatomic,strong)UIScrollView *bgScorllView;
@property(nonatomic,strong)JPProgressHUD *hub;

@end

@implementation WordAIViewController

-(AiChatManager *)aiChatManager{
    if(!_aiChatManager){
        _aiChatManager = [[AiChatManager alloc]init];
        _aiChatManager.delegate = self;
    }
    return _aiChatManager;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    self.hub = [JPProgressHUD showLoadingInView:self.view];
    [self loadAIData];
}

#pragma mark - 获取单词的词文串学
-(void)loadAIData{
    if(self.translateBtn.selected == YES){
        self.aiChatManager.type = 6;
        self.aiChatManager.content = self.contentStr;
    }else{
        self.aiChatManager.type = 5;
        NSMutableString *str = [NSMutableString string];
        for(NSInteger i = 0;i < self.dataArr.count;i++){
            WordListModel *model = self.dataArr[i];
            [str appendString:model.writing];
            if(i != self.dataArr.count-1){
                [str appendString:@","];
            }
        }
        self.aiChatManager.content = str;
    }
    [self.aiChatManager loadData];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:@"AI助记"];
    
    self.translateBtn = [[UIButton alloc]init];
    [self.translateBtn setTitle:@"翻译" forState:UIControlStateNormal];
    [self.translateBtn setTitleColor:KFontGrayColor forState:UIControlStateNormal];
    [self.translateBtn setTitleColor:KThemeColor forState:UIControlStateSelected];
    self.translateBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
    [self.translateBtn addTarget:self action:@selector(translateBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavigationBar addSubview:self.translateBtn];
    [self.translateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@42);
        make.height.mas_equalTo(@42);
        make.bottom.mas_equalTo(@-1);
        make.right.mas_equalTo(@-6);
    }];
    
    self.bgScorllView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT)];
    self.bgScorllView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bgScorllView];
    
    __weak typeof(self)weakSelf = self;

    self.contentLabel = [[UILabel alloc]init];
    self.contentLabel.backgroundColor = [UIColor whiteColor];
    self.contentLabel.numberOfLines = 0;
    [self.bgScorllView addSubview:self.contentLabel];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@20);
        make.top.mas_equalTo(@20);
        make.width.mas_equalTo(weakSelf.currentAvailableWidth-40);
        make.height.mas_equalTo(@0);
    }];
    
    self.translateLabel = [[UILabel alloc]init];
    self.translateLabel.backgroundColor = [UIColor whiteColor];
    self.translateLabel.numberOfLines = 0;
    [self.bgScorllView addSubview:self.translateLabel];
    [self.translateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@20);
        make.width.mas_equalTo(weakSelf.currentAvailableWidth-40);
        make.top.mas_equalTo(weakSelf.contentLabel.mas_bottom).offset(10);
        make.height.mas_equalTo(@0);
    }];
    
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if (isIPAD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            // 更新导航栏和背景视图的大小
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT);
            self.bgScorllView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            __weak typeof(self)weakSelf = self;
            if(self.translateBtn.selected == YES){
                CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                CGSize t_size = [self.translateLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                [self.translateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(weakSelf.contentLabel.mas_bottom).offset(10);
                    make.height.mas_equalTo(t_size.height);
                    make.width.mas_equalTo(weakSelf.currentAvailableWidth-40);
                }];
                self.bgScorllView.contentSize = CGSizeMake(self.currentAvailableWidth,54+c_size.height+t_size.height+10);
            }else{
                CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                [self.contentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(c_size.height);
                    make.width.mas_equalTo(weakSelf.currentAvailableWidth-40);
                }];
                self.bgScorllView.contentSize = CGSizeMake(self.currentAvailableWidth,54+c_size.height);
            }
        });
    }
}


- (NSMutableAttributedString *)changeText:(NSString *)text {
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 13;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
        NSForegroundColorAttributeName: KFontBlackColor,
        NSFontAttributeName:JPUIFontNotoSansJPRegular(16), // 字体和字体大小
        NSParagraphStyleAttributeName: paragraphStyle,
        NSKernAttributeName: @(2) // 设置字母间距为2px
    }];

    for (WordListModel *model in self.dataArr) {
        NSRange searchRange = NSMakeRange(0, text.length);
        NSRange foundRange;

        while (searchRange.location < text.length) {
            searchRange.length = text.length - searchRange.location;
            foundRange = [text rangeOfString:model.writing ? model.writing : @"" options:NSCaseInsensitiveSearch range:searchRange];

            if (foundRange.location != NSNotFound) {
                [attributedString addAttributes:@{
                    NSForegroundColorAttributeName: UIColorHex(0xFF781D),
                    NSParagraphStyleAttributeName: paragraphStyle,
                    NSKernAttributeName: @(2) // 继续使用相同的字母间距
                } range:foundRange];
                
                searchRange.location = foundRange.location + foundRange.length;
            } else {
                break;
            }
        }
    }
    
    return attributedString;
}

- (NSMutableAttributedString *)changeText2:(NSString *)text {
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 13;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
        NSForegroundColorAttributeName: KFontGrayColor,
        NSFontAttributeName:JPUIFontPingFangSCRegular(16), // 字体和字体大小
        NSParagraphStyleAttributeName: paragraphStyle,
        NSKernAttributeName: @(2) // 设置字母间距为2px
    }];
    return attributedString;
}



#pragma mark - 翻译
-(void)translateBtnClick{
    if(self.contentStr){
        self.translateBtn.selected = !self.translateBtn.selected;
        if(self.translateBtn.selected == NO){
            self.translateLabel.hidden = YES;
            CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
            self.bgScorllView.contentSize = CGSizeMake(self.currentAvailableWidth,54+c_size.height);
        }else{
            self.translateLabel.hidden = NO;
            //没有翻译数据才要去拿 有的话就直接显示
            if(self.translateBtn.selected == YES&&self.translateStr){
                CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                CGSize t_size = [self.translateLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                self.bgScorllView.contentSize = CGSizeMake(self.currentAvailableWidth,54+c_size.height+t_size.height+10);
            }else{
                self.hub = [JPProgressHUD showLoadingInView:self.view];
                [self loadAIData];
            }
        }
    }else{
        [JPProgressHUD showMsg:@"没有可翻译的内容"];
    }
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.aiChatManager]){
        NSDictionary *dic = manager.response.content;
        NSString *rcontent = [NSString stringWithFormat:@"%@",dic[@"message"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            if(self.hub){
                [self.hub removeFromSuperview];
            }
            // 在主线程执行的代码
            if(self.translateBtn.selected == YES){
                self.translateStr = rcontent;
                self.translateLabel.attributedText = [self changeText2:rcontent];
                CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                CGSize t_size = [self.translateLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                __weak typeof(self)weakSelf = self;
                [self.translateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(weakSelf.contentLabel.mas_bottom).offset(10);
                    make.height.mas_equalTo(t_size.height);
                }];
                self.bgScorllView.contentSize = CGSizeMake(self.currentAvailableWidth,54+c_size.height+t_size.height+10);
            }else{
                self.contentStr = rcontent;
                self.contentLabel.attributedText = [self changeText:rcontent];
                CGSize c_size = [self.contentLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
                [self.contentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(c_size.height);
                }];
                self.bgScorllView.contentSize = CGSizeMake(self.currentAvailableWidth,54+c_size.height);
            }
        });
     
    }
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(self.hub){
        [self.hub removeFromSuperview];
    }
    if(self.translateBtn.selected == YES){
        self.translateBtn.selected = NO;
    }
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

@end
